package com.shiku.imserver.repository.runnable;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.shiku.imserver.common.message.ChatMessage;
import com.shiku.imserver.repository.LastChatModel;
import com.shiku.imserver.repository.MessageRepository;
import com.shiku.imserver.service.IMBeanUtils;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LastMessageDBRunnable extends BaseRepositoryMapRunnable<ChatMessage> {
    private static final String LASTCHAT_MUC_COLLECTION = "lastChats_muc";
    private static Logger log = LoggerFactory.getLogger(LastMessageDBRunnable.class);
    protected ConcurrentHashMap<String, MongoCollection<Document>> dbMaps = new ConcurrentHashMap<>();
    private MongoDatabase lastMsgDB = IMBeanUtils.getBeanManager().getMongoClient().getDatabase(MessageRepository.LASTCHAT_DB);
    private MongoCollection<Document> lastMucCollection = this.lastMsgDB.getCollection(LASTCHAT_MUC_COLLECTION);
    protected ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public MongoCollection<Document> getMongoCollection(String userId) throws Exception {
        String collectionName = getCollectionName(userId);
        MongoCollection<Document> collection = (MongoCollection) this.dbMaps.get(collectionName);
        if (collection == null) {
            collection = this.lastMsgDB.getCollection(collectionName);
        }
        return collection;
    }

    public void putLastChat(ChatMessage message) {
        if (2 == message.getMessageHead().getChatType()) {
            addMsg(message.getMessageHead().getTo(), message);
        } else if (1 == message.getMessageHead().getChatType()) {
            addMsg(message.getFromUserId() + "_" + message.getToUserId(), message);
        }
    }

    public void runTask() {
        try {
            Iterator<Map.Entry<String, ChatMessage>> iterator = this.maps.entrySet().iterator();
            while (iterator.hasNext()) {
                refreshLastChat(iterator.next().getValue());
                try {
                    this.lock.writeLock().lock();
                    iterator.remove();
                    this.lock.writeLock().unlock();
                } catch (Exception e) {
                    log.error(e.toString(), e);
                    this.lock.writeLock().unlock();
                } catch (Throwable th) {
                    this.lock.writeLock().unlock();
                    throw th;
                }
            }
        } catch (Exception e2) {
            log.error(e2.toString(), e2);
        }
    }

    public void refreshLastChat(ChatMessage message) {
        LastChatModel lastChat;
        MongoCollection<Document> collection;
      // log.info("====refreshLastChat="+message.getContent()+",message.getMessageHead().getChatType()="+message.getMessageHead().getChatType());
        if (2 == message.getMessageHead().getChatType()) {
            lastChat = new LastChatModel();
            lastChat.setMessageId(message.getMessageHead().getMessageId());
            lastChat.setContent(message.getContent());
            lastChat.setUserId(message.getFromUserId());
            lastChat.setJid(message.getMessageHead().getTo());
            lastChat.setIsRoom(1);
            lastChat.setType(message.getType());
            lastChat.setTimeSend(message.getTimeSend());
            lastChat.setEncrypt(message.isEncrypt());
            lastChat.setFrom(message.getMessageHead().getFrom());
            lastChat.setTo(message.getMessageHead().getTo());
            lastChat.setFromUserName(message.getFromUserName());
            lastChat.setToUserName(message.getToUserName());
            lastChat.setToUserId(message.getToUserId());
        } else if (1 == message.getMessageHead().getChatType()) {
            lastChat = new LastChatModel();
            lastChat.setMessageId(message.getMessageHead().getMessageId());
            lastChat.setContent(message.getContent());
            lastChat.setUserId(message.getFromUserId());
            lastChat.setJid(message.getToUserId());
            lastChat.setIsRoom(0);
            lastChat.setType(message.getType());
            lastChat.setTimeSend(message.getTimeSend());
            lastChat.setEncrypt(message.isEncrypt());
            lastChat.setFrom(message.getMessageHead().getFrom());
            lastChat.setTo(message.getMessageHead().getTo());
            lastChat.setFromUserName(message.getFromUserName());
            lastChat.setToUserName(message.getToUserName());
        } else {
            return;
        }
        try {
            if (lastChat.getIsRoom() == 0) {
                collection = getMongoCollection(lastChat.getUserId());
            } else {
                collection = this.lastMucCollection;
            }
            Document query = new Document("jid", lastChat.getJid());
            Document values = new Document("type", Integer.valueOf(lastChat.getType()));
            values.append("messageId", lastChat.getMessageId());
            values.append("timeSend", Long.valueOf(lastChat.getTimeSend()));
            values.append("content", lastChat.getContent());
            values.append("userId", lastChat.getUserId());
            values.append("jid", lastChat.getJid());
            values.append("isRoom", Integer.valueOf(lastChat.getIsRoom()));
            values.append("isEncrypt", Boolean.valueOf(lastChat.isEncrypt()));
            values.append("from", lastChat.getFrom());
            values.append("to", lastChat.getTo());
            values.append("fromUserName", lastChat.getFromUserName());
            values.append("toUserName", lastChat.getToUserName());
            values.append("toUserID", lastChat.getToUserID());
            if (1 != lastChat.getIsRoom()) {
                query.append("userId", lastChat.getUserId());
            }
            if (0 < collection.count(query)) {
            	 
                collection.updateMany(query, new Document("$set", values));
                
            } else {
                collection.insertOne(values);
            }
            if (1 != lastChat.getIsRoom() && !lastChat.getUserId().equals(lastChat.getJid())) {
                if (1 != lastChat.getIsRoom()) {
                    query.replace("userId", lastChat.getJid());
                    query.replace("jid", lastChat.getUserId());
                    values.replace("userId", lastChat.getJid());
                    values.replace("jid", lastChat.getUserId());
                }
                values.remove("_id");
                try {
                    MongoCollection<Document> collection2 = getMongoCollection(lastChat.getJid());
                    if (0 < collection2.count(query)) {
                        collection2.updateMany(query, new Document("$set", values));
                    } else {
                        collection2.insertOne(values);
                    }
                } catch (NumberFormatException e) {
                    log.error("error {} ===> {} ", e.getMessage(), message.toString());
                } catch (Exception e2) {
                    log.error(e2.getMessage(), e2);
                }
            }
        } catch (NumberFormatException e3) {
            log.error("error {} ===> {} ", e3.getMessage(), message.toString());
        } catch (Exception e4) {
            log.error(e4.getMessage(), e4);
        }
    }
}
